package com.cc.visitor.entity.wechat;

import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlManageInstanceGroupStatement;
import com.cc.visitor.enums.DevMaterial;
import com.cc.visitor.utils.RestTemplateUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

/**
 * @author chanchaw
 * @create 2025-01-12 16:52
 */
@Component
public class MiniAccessTokenUtils implements Serializable {
    private static final long serialVersionUID = 1L;
    private static final Logger logger = LoggerFactory.getLogger("wxmp");
    private static final ObjectMapper mapper = new ObjectMapper();
    @Autowired
    private RestTemplateUtils restTemplateUtils;
    private static final String URL = "https://api.weixin.qq.com/cgi-bin/stable_token";
    private MiniAccessToken at = new MiniAccessToken();
    public MiniAccessToken getAccessToken(){
        HashMap<String, Object> map = new HashMap<>();
        map.put("grant_type","client_credential");
        map.put("appid", DevMaterial.VISITOR_MINI.APPID);
        map.put("secret",DevMaterial.VISITOR_MINI.APPSECRET);
        map.put("force_refresh",false);

//        String szToken = restTemplateUtils.get4Object(URL,String.class);
        MiniAccessToken miniAccessToken = null;
        try {
            miniAccessToken = restTemplateUtils.postJson(URL,map,MiniAccessToken.class);
        } catch (JsonProcessingException e) {
            System.out.println("请求小程序 access_token 时出现异常：" + e.getMessage());
            throw new RuntimeException(e);
        }
        System.out.println("请求微信服务器mini access token得到的响应结果是：" + miniAccessToken.toString());
        logger.info("请求微信服务器mini access token得到的响应结果是：{}", miniAccessToken.toString());
        at.setAccess_token(miniAccessToken.getAccess_token());
        at.setExpires_in(Long.valueOf(miniAccessToken.getExpires_in()));
        return at;
    }
}
